import time
from datetime import datetime
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils import timezone

from golf import models


def index(req):
    """HOME页面操作"""
    day = time.strftime( "%Y-%m-%d", time.localtime() )
    mon = time.strftime( "%Y-%m", time.localtime() )
    info = req.session.get( "info" )
    list = models.yardinfo.objects.all()
    return render( req, "golf_index.html",{"yards":list})


def invoice(req,nid):
    list = models.memberinfo.objects.all()
    yard = models.yardinfo.objects.filter(id=nid).first()
    now = timezone.now()
    endtime = now.strftime( "%Y-%m-%d %H:%M:%S" )
    times = datetime.strptime(endtime,"%Y-%m-%d %H:%M:%S") -yard.starttime
    if req.method == "POST":
        member = req.POST.get("member")
        money = req.POST.get("money")
        print(member)
        n = 0
        if member!="":
            memberinfo = models.memberinfo.objects.filter(phone=member).first()
            models.saleinfo.objects.create( starttime=yard.starttime, endtime=endtime, yard_id=nid, price=money ,member_id=memberinfo.id)
            balance = memberinfo.balance
            n = int(balance) - int(money)
            models.memberinfo.objects.filter(id = memberinfo.id).update(balance =n)
            sendMail( memberinfo.phone, memberinfo.name, money, n )
        else:
            models.saleinfo.objects.create( starttime=yard.starttime, endtime=endtime, yard_id=nid, price=money)
        models.yardinfo.objects.filter( id=nid ).update( isty=1 )
        re = {"re": "结算成功"}
        return JsonResponse( re )
    return render(req,"golf_member_select.html",{"list":list,"nid":nid,"yard":yard,"endtime":endtime,"times":times})

def findMemberByPhone(req):
    phone = req.POST.get("phone")
    member = models.memberinfo.objects.values().filter(phone=phone)
    if member != None:
        j = list( member )
        print( j )
        return JsonResponse( j, safe=False )
    else:
        re = {"re": "未查到单据，或单据已发生退货"}
    return JsonResponse( re )


def yardStart(req):
    id = req.POST.get('id')
    print(id)


    now = timezone.now()
    models.yardinfo.objects.filter(id=id).update(isty = 0,starttime=now.strftime("%Y-%m-%d %H:%M:%S"))
    re = {"re": True}
    return JsonResponse( re )

def yardEnd(req):
    id = req.POST.get('id')
    print(id)
    models.yardinfo.objects.filter(id=id).update(isty = 1)
    re = {"re": True}
    return JsonResponse( re )



def sendMail(phone,name,money,balance):
    import requests
    import json

    appid = '89472'  # SUBMAIL控制台创建appid
    appkey = '7ee3d241285a0a490eef2210491a1dca'  # SUBMAIL控制台获取appkey
    project = 'zrdLC2'  # SUBMAIL控制台创建模板 获取模板id
    to = phone  # 手机号码

    url = 'https://api-v4.mysubmail.com/sms/xsend.json'

    header = {"Content-type": "application/json"}
    vars = {
        'name':name,
        'num': money,  # code为参数名 和模板中参数名一致
        'num2': balance  # time为参数名 和模板中参数名一致
    }
    param = {
        'appid': appid,
        'signature': appkey,
        'project': project,
        'to': to,
        'vars': json.dumps( vars )
    }
    res = requests.post( url, data=json.dumps( param ), headers=header )
    print( res.json() )
    return True